package com.company.cloud.sdk.weixin.open;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.company.cloud.sdk.weixin.common.constant.WxErrorEnum;
import com.company.cloud.sdk.weixin.common.exception.WxException;
import com.company.cloud.sdk.weixin.open.enums.WxOpenApiType;
import com.company.cloud.sdk.weixin.open.enums.WxOpenDomain;
import com.company.cloud.sdk.weixin.open.model.Code2AccessTokenModel;
import com.company.cloud.sdk.weixin.open.model.Code2AccessTokenResp;

import java.util.Map;

public class WxOpenApi {

    public static String getReqUrl(WxOpenApiType wxOpenApiType){
        return getReqUrl(wxOpenApiType,null);
    }

    public static String getReqUrl(WxOpenApiType wxOpenApiType, WxOpenDomain wxOpenDomain){
        if(wxOpenDomain==null){
            wxOpenDomain=WxOpenDomain.CHINA;
        }
        return  wxOpenDomain.getType().concat(wxOpenApiType.getType());
    }


    /**
     * 通过code换取网页授权access_token(openId)
     * */
    public static String code2AccessToken(Map<String, Object> params){
        try {
            String url=getReqUrl(WxOpenApiType.Get_OpenId);
            String httpResp= HttpUtil.get(url,params);
            return  httpResp;
        }catch (Exception e){
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(),e.getMessage());
        }
    }

    /**
     * 通过code换取网页授权access_token(openId)
     * */
    public static Code2AccessTokenResp code2AccessToken(Code2AccessTokenModel entity){
        Map<String, Object> params =  BeanUtil.beanToMap(entity,false,true);
        String result= WxOpenApi.code2AccessToken(params);
        if(StrUtil.isEmpty(result)){
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String,Object> resultMap= JSON.parseObject(result, Map.class);
        Code2AccessTokenResp data= BeanUtil.fillBeanWithMapIgnoreCase(resultMap,new Code2AccessTokenResp(),false);
        if(data.getErrcode()!=null && data.getErrcode()!=0){
            throw new WxException(data.getErrcode(),data.getErrmsg());
        }
        return data;
    }


//    /**
//     * 刷新网页授权access_token
//     * */
//    public  RefreshTokenResp refreshToken(RefreshTokenModel params){
//        return null;
//    }





}
